package com.kx.game.center;

import com.genchance.core.dawn.global.ConstantData;
import com.kx.core.dawn.dbs.dao.DaoManager;
import com.kx.core.dawn.dbs.entity.GameServerEntity;
import com.kx.game.center.async.ListenerServer;
import com.kx.game.center.dbs.DBServices;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.manager.AsyncTaskManager;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebListener;
import java.util.*;

@WebListener
public class CenterServer implements ServletContextListener {

    private static Logger logger = LoggerFactory.getLogger(CenterServer.class);

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        ConstantData.configPath = GSServices.serverConfig.getResourcePath();
//        PropertyConfigurator.configureAndWatch(ConstantData.configPath + "log4j.properties");
        //初始化DB
        initDB();
        //初始化异步线程
        initAsyncThread();
        logger.info(" ========================= 服务初始完成");
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        //关服释放
//        Map<String, SqlSessionFactory> dbSessionFactorys = DBServices.getDbSessionFactorys();
//        dbSessionFactorys.forEach((k,v)-> {dbSessionFactorys.get(k).getConfiguration().});
//        dbSessionFactorys.clear();
        // 异步任务执行器结束
        AsyncTaskManager.getInstance().shutDown();
    }

    private void initAsyncThread() {
        new ListenerServer();
    }

    public void initDB() {
        DBServices dbServices = new DBServices();
        DaoManager.initTable(dbServices.myServerId);
        List<GameServerEntity> gameServers = DaoManager.gameServerDao.findAll();
        for (GameServerEntity gameServer : gameServers) {
            dbServices.getDbSessionFactorys().put(gameServer.getServerId() + "", dbServices.init(
                    DBServices.sql_Config,
                    ConstantData.configPath + DBServices.db_pool_Config,
                    gameServer.getConnectIp(), gameServer.getConnectPort()));
        }
        //检查redis数据库完整性
        GSServices.loadManager.overLoadingRedis(gameServers);
        logger.info(" ========================= 数据初始完成");
    }
}
